package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileWriter;
import org.apache.lucene.index.CorruptIndexException;

import datastructure.Querystruct;
import datastructure.sentence;
import result.ResultExtractor;
import idx.Searcher;
public class Main {
	public static Hashtable<String,Integer> stopword;
	public static void main(String [] args) throws CorruptIndexException, IOException
	{
		BufferedReader read = new BufferedReader(new FileReader(new File("stopword.txt")));
		BufferedReader reader = new BufferedReader(new FileReader(new File("test.xml")));
		stopword = new Hashtable<String,Integer>();
		String line = "";
		String test = "";
		while((line = read.readLine()) != null)
		{
			line = line.replaceAll(" ", "\t");
			String[] words = line.split("\t");
			if(words.length == 3)
			{
				int rank = Integer.parseInt(words[2]);
				if(rank < 10000)
				{
					stopword.put(words[0], rank);
				}
			}
		}
		System.out.println(stopword.size());
		read.close();
		while ((line = reader.readLine()) != null)
		{
			test += line + "\n";
		}
		reader.close();
		Pattern p=Pattern.compile("<q>(.*?)</q>");//也可满足中文双引号里的匹配
        Matcher m=p.matcher(test);
        Vector<String> querys = new Vector<String>();
        while(m.find()){
        	//System.out.println(m.group(1).toString());
			querys.add(m.group(1).toString().replace(",", "，").replaceAll("我国", "中国"));
        }
        FileWriter writer = new FileWriter("testresult");
        Searcher s = new Searcher(Integer.parseInt(args[1]), args[0]);
        for(int j = 250; j < 300; j++)
        {
			
			//Scanner sc = new Scanner(System.in);
			System.out.println(j+1 + ":" + querys.elementAt(j));
			sentence query = new sentence(querys.elementAt(j).trim());
			Querystruct Query = new Querystruct(query, false);//combine words or not
			System.out.println(Query.tag_content);
			String q = "";
			for(int i = 0; i < Query.keyword.size(); i++)
				q += Query.keyword.get(i).content + " ";
			System.out.println(q);
			s.Search("context", Query);
			File [] hitFile = new File[s.docs.length];
			for(int i = 0; i < hitFile.length; i++)
			{
				hitFile[i] = new File("/media/My Passport/"+s.docs[i].get("path").substring(23));
				//System.out.println(s.docs[i].get("title"));
				//hitFile[i] = new File(s.docs[i].get("path"));
			}
			ResultExtractor re = new ResultExtractor();
			writer.write((j+1) + ":" + querys.elementAt(j) + ":" + re.TopNSentence(Query, hitFile, 10) + "\n");
			writer.flush();
			for(int i = 0 ; i < hitFile.length; i++)
				hitFile[i] = null;
			re = null;
			System.gc();
        }
        
        
		return;
		
	}
}
